import preferences from '@ohos.data.preferences'
class PrefrenceUtils{

   prefMap:Map<string,preferences.Preferences> = new Map()
  /**
   * 初始化preferences
   * @param context
   * @param name
   */
   async  loafPrefrence(context,name:string){
     try {
       let pref = await  preferences.getPreferences(context,name)
       console.log("testTag",'加载preferences'+name+'成功')
       this.prefMap.set(name,pref)
     }catch (e){
       console.log("testTag",'加载preferences'+name+'失败:'+e)
     }
   }
  /**
   * 以键值对的方式存储数据
   * @param name
   * @param key
   * @param value
   */
  async  putData(name:string,key:string,value:preferences.ValueType){
      if(!this.prefMap.has(name)){
        console.log("testTag",'preferences'+name+'尚未初始化')
        return
      }
    try {
      let prof = this.prefMap.get(name)
      //存数据
      await prof.put(key,value)
      //刷入磁盘
      await prof.flush()
      console.log("testTag",'preferences'+name+'保存数据成功')
    }catch (e){
      console.log("testTag",'preferences'+name+'保存数据失败:'+JSON.stringify(e))
    }
  }
  /**
   * 通过Key获取数据
   * @param name
   * @param key
   * @param defaultValue
   * @returns
   */
  async  getData(name:string,key:string,defaultValue:preferences.ValueType){
    if(!this.prefMap.has(name)){
      console.log("testTag",'preferences'+name+'尚未初始化')
      return
    }
    try {
      let prof = this.prefMap.get(name)
      //取数据
      let value =  await prof.get(key,defaultValue)
      console.log("testTag",'preferences'+name+'取数据成功')
      return value
    }catch (e){
      console.log("testTag",'preferences'+name+'取数据失败:'+JSON.stringify(e))
    }
  }
  /**
   * 通过key删除数据
   * @param name
   * @param key
   */
  async  deletData(name:string,key:string){
    if(!this.prefMap.has(name)){
      console.log("testTag",'preferences'+name+'尚未初始化')
      return
    }
    try {
      let prof = this.prefMap.get(name)
      //删除数据
      await prof.delete(key)
      console.log("testTag",'preferences'+name+'删除数据成功')
    }catch (e){
      console.log("testTag",'preferences'+name+'删除数据失败:'+JSON.stringify(e))
    }
  }
}

const  prefrenceUtils = new PrefrenceUtils()
export default prefrenceUtils